//
//  PhysicSystem.m
//  Project 5
//
//  Created by Nguyen Tan Loc on 6/17/13.
//  Copyright (c) 2013 Nguyen Tan Loc. All rights reserved.
//

#import "PhysicSystem.h"

@implementation PhysicSystem

static PhysicSystem *m_Instance = nil;

+(PhysicSystem *) sharedPhysicSystem
{
    if (m_Instance == nil)
        m_Instance = [[PhysicSystem alloc] init];
    return m_Instance;
}

-(id) init
{
    if (self = [super init])
    {
        mListObjectCircle = [[NSMutableArray alloc] init];
        mListObjectBullet = [[NSMutableArray alloc] init];
    }
    return self;
}

-(void) addBodyToSystem:(PhysicBody *)body withType:(PhysicObjectType)type
{
    if (type == TYPE_PHYSIC_OBJECT_CIRCLE)
    {
        [mListObjectCircle addObject:body];
    }
    else if (type == TYPE_PHYSIC_OBJECT_BULLET)
    {
        [mListObjectBullet addObject:body];
    }
}

-(void) removeBodyFromSystem:(PhysicBody *)body
{
    [mListObjectCircle removeObject:body];
    [mListObjectBullet removeObject:body]; // not test yet
}

-(void) removeAllBody
{
    [mListObjectCircle removeAllObjects];
    [mListObjectBullet removeAllObjects];
}

-(void) update
{
    for (int i = 0; i < mListObjectBullet.count; i++)
    {
        PhysicBody *bulletBody = [mListObjectBullet objectAtIndex:i];
        if ([bulletBody._delegate isCheckCollision] == NO) continue;
        
        for (int j = 0; j < mListObjectCircle.count; j++)
        {
            Boolean isCollide = NO;
            PhysicBody *circleBody = [mListObjectCircle objectAtIndex:j];
            if ([circleBody._delegate isCheckCollision] == NO) continue;
            
            if (bulletBody._shapeType == SHAPE_TYPE_LINE)
            {
                if ([self checkCollisionCircle:circleBody withCircle:bulletBody])
                    isCollide = YES;
            }
            else
            {
                if ([self checkCollisionCircle:circleBody withCircle:bulletBody])
                    isCollide = YES;
            }
            
            if (isCollide)
            {
                [bulletBody._delegate beginContact:circleBody._delegate];
                [circleBody._delegate beginContact:bulletBody._delegate];
            }
        }
    }
}

-(Boolean) checkCollisionCircle:(PhysicBody *)bodyc1 withCircle:(PhysicBody *)bodyc2
{
    float distance = ccpLength(ccp(bodyc1.getPosition.x - bodyc2.getPosition.x, bodyc1.getPosition.y - bodyc2.getPosition.y));
    distance -= (bodyc1._value + bodyc2._value);
    
    if (distance > 0)
        return NO;
    else
        return YES;
}

-(Boolean) checkCollisionCircle:(PhysicBody *)bodyc1 withLine:(PhysicBody *)bodyl2
{
    return NO;
}

@end
